package executorDemo;

import cn.hutool.core.thread.ThreadUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

public class ExecutorDemo {

    private Map<String, String> concurrentHashMap = new ConcurrentHashMap<>();

    /**
     * 读少写多的情况下
     * 读写删除加锁，且加锁在代码块上，效率较好，遍历未加锁
     */
    private List<String> moreWriteList = Collections.synchronizedList(new ArrayList<>());

    /**
     * 读多写少的情况下
     * 读未加锁
     */
    private CopyOnWriteArrayList<String> moreReadList = new CopyOnWriteArrayList<>();

    /**
     * 线程安全的int
     * atomicInteger.incrementAndGet()
     * atomicInteger.getAndAdd(1)
     */
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public static void main(String[] args) {
        //计算密集型，阻塞系数设置为0.5；IO密集型，阻塞系数设置为0.8或更大
        ExecutorService executor = ThreadUtil.newExecutorByBlockingCoefficient(0.5F);
        long startTime = System.nanoTime();
        for (int i = 0; i < 1000; i++) {
            executor.execute(() -> System.out.println("aaa"));
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        long endTime = System.nanoTime();
        System.out.println("耗时：" + (endTime - startTime));
    }

}
